package com.itheima.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.itheima.excel.listen.CommonListen;
import com.itheima.excel.pojo.UserModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/5/2 9:31
 **/
@RequestMapping("user")
@RestController
public class UserImportController {

    @RequestMapping("export")
    //获取url链接上的参数
    public String dowm(HttpServletResponse response, @RequestParam("name") String name){
        response.setContentType("application/binary;charset=UTF-8");
        try{
            ServletOutputStream out=response.getOutputStream();
            try {
                //设置文件头：最后一个参数是设置下载文件名(这里我们叫：张三.pdf)
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            List list = Arrays.asList(
                    new UserModel("小明",20,"男"),
                    new UserModel("小花",20,"男"),
                    new UserModel("小天",20,"男"),
                    new UserModel("小率",20,"男"),
                    new UserModel("小帅",20,"男"),
                    new UserModel("小憨",20,"男"),
                    new UserModel("小呆",20,"男")
            );
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            // 如果这里想使用03 则 传入excelType参数即可
            EasyExcel.write(out, UserModel.class).sheet("模板").doWrite(list);
            return "success";
        } catch(Exception e){
            e.printStackTrace();
            return "导出信息失败";
        }
    }
    @PostMapping("/import")
    public void simpleRead(MultipartFile file) throws IOException {
        CommonListen<UserModel> commonListen1 = new CommonListen<UserModel>();
        CommonListen<UserModel> commonListen2 = new CommonListen<UserModel>();
        EasyExcel.read(file.getInputStream(), UserModel.class, commonListen1).sheet(0).doRead();
        EasyExcel.read(file.getInputStream(), UserModel.class, commonListen2).sheet(1).doRead();
        // 获取导入的数据集合
        List<UserModel> list1 = commonListen1.getList();
        List<UserModel> list2 = commonListen2.getList();
        // 打印所有导入的数据
        list1.forEach(System.out::println);
        list2.forEach(System.out::println);
    }
}
